<template>
  <div class="common_wrap">
    <div class="common_title">任务管理</div>
    <div class="btn_group">
      <el-button type="primary" @click="add">添加子任务</el-button>
    </div>
    <div class="content">
      <el-tree ref="tree" :props="props" :data="treeData" node-key="id">
        <div class="custom-tree-node" slot-scope="{ node, data }">
          <div class="tree-node-title">
            <div>{{ data.name }}</div>
            <div class="tree-node-btn-group">
              <i class="el-icon-delete" @click.stop="delNode(data)"></i>
              <i
                class="el-icon-edit-outline"
                @click.stop="editNode(data, node)"
              ></i>
              <!-- 非任务节点可添加子节点 -->
              <i
                v-if="data.catalogType == 0"
                class="el-icon-circle-plus"
                @click.stop="addChildrenNode(data)"
              ></i>
            </div>
          </div>
          <!-- 任务节点展示人员 -->
          <div
            class="person-list"
            v-if="data.catalogType == 1"
            style="margin-left: 12px"
          >
            <div
              class="red-list"
              v-if="data.receiptDoList.filter((v) => v.dutyType == 0).length"
            >
              红牌责任人（{{
                data.receiptDoList.filter((v) => v.dutyType == 0).length
              }}人）：
              <div
                v-for="(item, index) in data.receiptDoList.filter(
                  (v) => v.dutyType == 0
                )"
                :key="index"
                style="
                  border: solid 1px #ddd;
                  display: inline-block;
                  border-radius: 20px;
                  padding: 0 5px;
                  background: #ddd;
                  margin: 3px;
                "
              >
                {{ item.empName }} {{ item.empArea }} {{ item.empPost }}
              </div>
            </div>
            <div
              class="green-list"
              v-if="data.receiptDoList.filter((v) => v.dutyType == 1).length"
              style="margin-top: 5px"
            >
              绿牌责任人（{{
                data.receiptDoList.filter((v) => v.dutyType == 1).length
              }}人）：
              <div
                v-for="(item, index) in data.receiptDoList.filter(
                  (v) => v.dutyType == 1
                )"
                :key="index"
                style="
                  border: solid 1px #ddd;
                  display: inline-block;
                  border-radius: 20px;
                  padding: 0 5px;
                  background: #ddd;
                  margin: 3px;
                "
              >
                {{ item.empName }} {{ item.empArea }} {{ item.empPost }}
              </div>
            </div>
          </div>
        </div>
      </el-tree>
    </div>
    <el-dialog title="操作任务节点" :visible.sync="dialogVisible" width="50%">
      <el-form
        ref="task"
        :model="operateTaskNode"
        label-width="120px"
        class="search-nav"
        :rules="taskRules"
      >
        <el-form-item prop="parentTitle" label="所属上级：">
          <el-input
            v-model="operateTaskNode.parentTitle"
            maxlength="255"
            placeholder="请输入所属上级"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item prop="title" label="任务名称：">
          <el-input
            v-model="operateTaskNode.title"
            maxlength="255"
            placeholder="请输入任务名称"
          ></el-input>
        </el-form-item>
        <el-form-item prop="catalogType" label="任务类型：">
          <el-radio-group
            v-model="operateTaskNode.catalogType"
            :disabled="query.parentId != operateTaskNode.parentId"
          >
            <el-radio label="0">目录</el-radio>
            <el-radio label="1">任务</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="sort" label="排序：">
          <el-input-number
            v-model="operateTaskNode.sort"
            :min="1"
            :max="1000"
            :precision="0"
          ></el-input-number>
        </el-form-item>
        <el-form-item
          prop="redList"
          label="红牌责任人："
          v-if="operateTaskNode.catalogType === '1'"
        >
          <el-select
            v-model="operateTaskNode.redList"
            placeholder="请选择红牌责任人"
            filterable
            clearable
            multiple
            @change="(list) => changePerson(list, 1)"
            style="width: 100%"
          >
            <el-option
              v-for="(item, index) in redPersonList"
              :key="index"
              :value="item.empId"
              :label="
                item.name +
                ' ' +
                (item.areaName || '') +
                ' ' +
                (item.streetName || '') +
                ' ' +
                (item.govEmpPosJob || '')
              "
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          prop="greenList"
          label="绿牌责任人："
          v-if="operateTaskNode.catalogType === '1'"
        >
          <el-select
            v-model="operateTaskNode.greenList"
            placeholder="请选择绿牌责任人"
            filterable
            clearable
            multiple
            @change="(list) => changePerson(list, 2)"
            style="width: 100%"
          >
            <el-option
              v-for="(item, index) in greenPersonList"
              :key="index"
              :value="item.empId"
              :label="
                item.name +
                ' ' +
                (item.areaName || '') +
                ' ' +
                (item.streetName || '') +
                ' ' +
                (item.govEmpPosJob || '')
              "
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelTaskNode">取 消</el-button>
        <el-button type="primary" @click="warningType">确 定</el-button>
      </span></el-dialog
    >
  </div>
</template>


<script>
export default {
  name: "marketManageAdd",
  data() {
    return {
      dialogVisible: false,
      props: {
        label: "name",
        children: "childList",
        isLeaf: "catalogType",
      },
      treeData: [
        {
          id: 1,
          label: "1",
          status: false,
          children: [],
        },
        {
          id: 2,
          label: "2",
          status: true,
          redPersonList: [
            {
              id: 100,
              name: "red1",
            },
          ],
          greenPersonList: [
            {
              id: 200,
              name: "green1",
            },
          ],
        },
      ],
      operateTaskNode: {
        parentId: "",
        parentTitle: "",
        sort: 1,
      },
      query: {},
      taskRules: {
        parentTitle: [
          { required: true, message: "请输入所属上级", trigger: "blur" },
        ],
        title: [{ required: true, message: "请输入任务名称", trigger: "blur" }],
        catalogType: [
          { required: true, message: "请选择任务类型", trigger: "change" },
        ],
        sort: [{ required: true, message: "请输入排序", trigger: "blur" }],
        // redList: [
        //   { required: true, message: "请选择红牌责任人", trigger: "change" },
        // ],
        // greenList: [
        //   { required: true, message: "请选择绿牌责任人", trigger: "change" },
        // ],
      },
      personList: [],
      taskType: "",
    };
  },
  watch: {},
  computed: {
    redPersonList() {
      return this.personList.filter((v) => v.status !== 2);
    },
    greenPersonList() {
      return this.personList.filter((v) => v.status !== 1);
    },
  },
  created() {
    this.query = this.$route.query;
    this.operateTaskNode = this.query;
    this.getEmpList();
    this.getTreeData();
  },
  methods: {
    getEmpList() {
      const params = {
        page: 1,
        limit: 9999,
        type: 0,
      };
      this.$api.roleAllList(params).then((res) => {
        if (res.status === 200) {
          this.personList = res.data.data.items;
        }
      });
    },
    getTreeData() {
      this.$api
        .treeTask({
          mainId: this.query.parentId,
        })
        .then((res) => {
          if (res.status === 200) {
            this.treeData = res.data.data;
          } else {
            this.treeData = [];
          }
        })
        .catch(() => {
          this.treeData = [];
        });
    },
    add() {
      this.operateTaskNode = {
        catalogType: "0",
        ...this.query,
        sort: 1,
        redList: [],
        greenList: [],
      };
      this.dialogVisible = true;
    },
    cancelTaskNode() {
      this.dialogVisible = false;
      this.operateTaskNode = {
        catalogType: "0",
        ...this.query,
        sort: 1,
        redList: [],
        greenList: [],
      };
    },
    warningType() {
      if (
        this.operateTaskNode.id &&
        this.operateTaskNode.catalogType != this.taskType
      ) {
        this.$confirm(
          "修改任务类型会删除之前保存的对应数据，确定修改吗?",
          "警告",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          .then(() => this.submitTaskNode())
          .catch(() => {});
      } else {
        this.submitTaskNode();
      }
    },
    submitTaskNode() {
      // 表单校验
      this.$refs.task.validate(async (valid) => {
        if (!valid) return;
        console.log(this.operateTaskNode, "save");
        this.operateTaskNode.mainId = this.query.parentId;
        // 别问  问就是  懒得跟后端bb
        this.operateTaskNode.dutyReceiptList = [];
        for (const id of this.operateTaskNode.greenList) {
          this.operateTaskNode.dutyReceiptList.push({
            empId: id,
            dutyType: 1,
          });
        }
        for (const id of this.operateTaskNode.redList) {
          this.operateTaskNode.dutyReceiptList.push({
            empId: id,
            dutyType: 0,
          });
        }
        if (
          this.operateTaskNode.catalogType == 1 &&
          this.operateTaskNode.dutyReceiptList.length === 0
        ) {
          return this.$message.error("请选择至少一个责任人");
        }
        if (this.query.parentId === this.operateTaskNode.parentId) {
          this.operateTaskNode.parentId = null;
        }
        // =======
        this.$api.addTree(this.operateTaskNode).then((res) => {
          if (res.status === 200) {
            this.$message.success("成功保存子任务");
            this.dialogVisible = false;
            this.getTreeData();
            this.getEmpList();
          }
        });
        // http ...
        // this.operateTaskNode = {
        //   catalogType: "0",
        //   ...this.query,
        //   sort: 1,
        //   redList: [],
        //   greenList: [],
        // };
        // this.dialogVisible = false;
        // ...
      });
    },
    delNode(node) {
      console.log("delNode", node);
      this.$confirm(
        `删除此节点，会一并删除其子节点，确定删除“${node.name}”吗？`,
        "删除",
        {
          confirmButtonText: "删除",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          console.log("delOK");
          this.$api.delTree({ itemId: node.id }).then((res) => {
            if (res.status === 200) {
              this.$message.success("删除成功");
              this.getTreeData();
            }
          });
        })
        .catch(() => {
          console.log("delNO");
        });
    },
    editNode(node, treeNode) {
      this.taskType = node.catalogType;
      console.log("editNode", node, treeNode);
      this.operateTaskNode = {
        id: node.id,
        catalogType: String(node.catalogType),
        sort: node.sort || 1,
        title: node.name,
        parentId: treeNode.parent.data.id || this.query.parentId,
        parentTitle: treeNode.parent.data.name || this.query.parentTitle,
        mainId: node.mainId,
        redList: [],
        greenList: [],
      };
      if (node.catalogType == 1) {
        this.operateTaskNode.redList = node.receiptDoList
          .filter((v) => v.dutyType == 0)
          .map((v) => v.empId);
        this.operateTaskNode.greenList = node.receiptDoList
          .filter((v) => v.dutyType == 1)
          .map((v) => v.empId);
      }
      console.log(this.operateTaskNode);
      this.dialogVisible = true;
    },
    addChildrenNode(node) {
      console.log("addChildrenNode", node);
      this.operateTaskNode = {
        catalogType: "1",
        sort: 1,
        redList: [],
        greenList: [],
        parentId: node.id,
        parentTitle: node.name,
      };
      this.dialogVisible = true;
    },
    changePerson(list, status) {
      for (const person of this.personList) {
        // 清空状态
        if (person.status === status) {
          this.$set(person, "status", 0);
        }
        // 添加状态
        if (list.includes(person.empId)) {
          this.$set(person, "status", status);
        }
      }
    },
  },
};
</script>


<style scoped>
>>> .el-tree-node__content {
  height: auto !important;
  align-items: flex-start;
}
>>> .el-tree-node {
  white-space: normal;
}
.tree-node-title {
  display: flex;
  align-items: center;
}
.tree-node-btn-group {
  margin-left: 12px;
}
.tree-node-btn-group > i {
  margin: 0 5px;
}
</style>